package com.benshou.bsoa.service.yida;


import com.aliyun.dingtalkyida_2_0.Client;
import com.aliyun.dingtalkyida_2_0.models.SearchFormDataSecondGenerationHeaders;
import com.aliyun.dingtalkyida_2_0.models.SearchFormDataSecondGenerationRequest;
import com.aliyun.dingtalkyida_2_0.models.SearchFormDataSecondGenerationResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.benshou.bsoa.dto.yida.req.YiDaSearchReq;
import com.benshou.bsoa.utils.CreateAccessTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/*
 *  宜搭相关表单实例搜索
 */
@Service
public class SearchYiDaService {

    @Value("${yida_app_code}")
    private String APP_CODE;

    @Value("${yida_app_secret}")
    private String APP_SECRET;

    @Autowired
    private CreateAccessTokenUtil createAccessTokenUtil;
    /**
     * 搜索宜搭表单数据（不含子表字段）。
     *
     * @param req 封装的搜索请求参数
     * @return SearchFormDataSecondGenerationNoTableFieldResponse 搜索结果
     * @throws Exception 若请求失败则抛出异常
     */
    public SearchFormDataSecondGenerationResponse searchFormData(YiDaSearchReq req) throws Exception {
        // 创建 Client
        Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        Client client = new Client(config);

        SearchFormDataSecondGenerationHeaders headers = new SearchFormDataSecondGenerationHeaders();
        headers.xAcsDingtalkAccessToken = createAccessTokenUtil.getToken();

        SearchFormDataSecondGenerationRequest request = new SearchFormDataSecondGenerationRequest()
                .setPageNumber(req.getPageNumber())
                .setPageSize(req.getPageSize())
                .setFormUuid(req.getFormUuid())
                .setSystemToken(APP_SECRET)
                .setAppType(APP_CODE)
                .setUserId(req.getUserId())
                .setSearchCondition(req.getSearchCondition())
                .setOrderConfigJson(req.getOrderConfigJson())
                .setOriginatorId(req.getOriginatorId())
                .setCreateFromTimeGMT(req.getCreateFromTimeGMT())
                .setCreateToTimeGMT(req.getCreateToTimeGMT())
                .setModifiedFromTimeGMT(req.getModifiedFromTimeGMT())
                .setModifiedToTimeGMT(req.getModifiedToTimeGMT());


        try {
            return  client.searchFormDataSecondGenerationWithOptions(request, headers, new com.aliyun.teautil.models.RuntimeOptions());
        } catch (TeaException err) {
            throw new RuntimeException("搜索表单数据时发生错误: " + err.getMessage(), err);
        } catch (Exception e) {
            TeaException err = new TeaException(e.getMessage(), e);
            throw new RuntimeException("搜索表单数据时发生异常: " + err.getMessage(), err);
        }
    }

}
